package 密码学实验;

public class ShiftRegisterCipher {
    private int[] register;
    private int position;

    public ShiftRegisterCipher() {
        // 初始化5位移位寄存器
        register = new int[]{1, 1, 0, 0, 1};
        position = 0;
        // 预生成31位密钥流
        for (int i = 5; i < 31; i++) {
            register[i % register.length] = (register[(i-2) % register.length]
                    + register[(i-5) % register.length]) % 2;
        }
    }

    public String encrypt(String text) {
        return process(text);
    }

    public String decrypt(String text) {
        return process(text);
    }

    private String process(String text) {
        StringBuilder result = new StringBuilder();
        for (char c : text.toCharArray()) {
            int keyByte = generateKeyByte();
            result.append((char)(c ^ keyByte));
        }
        position = 0; // 重置位置
        return result.toString();
    }

    private int generateKeyByte() {
        int key = 0;
        for (int i = 0; i < 8; i++) {
            key = (key << 1) | register[position % register.length];
            position = (position + 1) % register.length;
        }
        return key;
    }

    public static void main(String[] args) {
        ShiftRegisterCipher cipher = new ShiftRegisterCipher();
        String original = "Hello123";
        String encrypted = cipher.encrypt(original);
        String decrypted = cipher.decrypt(encrypted);

        System.out.println("原始: " + original);
        System.out.println("加密: " + encrypted);
        System.out.println("解密: " + decrypted);
    }
}